package tbdp.tool;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Collections2;
import com.google.common.collect.Maps;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import tbdp.tool.common.Constants;
import tbdp.tool.common.Utils;

import javax.annotation.Nullable;
import java.io.File;
import java.io.FilenameFilter;
import java.util.*;

/**
 * Created by xbkaishui on 16/10/16.
 * 文件合并操作
 */
public class Merge {

    private static final Logger log = Logger.getLogger(Merge.class);

    /**
     * 返回合并后的文件列表
     *
     * @param dirPath
     * @param finalFileName
     * @return
     */
    public static List<String> merge(String dirPath, String finalFileName) {

        if (StringUtils.isEmpty(finalFileName)) {
            finalFileName = "final.out";
        }

        File dir = new File(dirPath);
        File[] files = dir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(Constants.txtSuffix);
            }
        });

        Map<String, File> filesMap = Maps.uniqueIndex(Arrays.asList(files), new Function<File, String>() {
            public String apply(@Nullable File input) {
                return input.getName();
            }
        });

        List<String> namesSort = new ArrayList<String>(filesMap.keySet());
        Collections.sort(namesSort);
        System.out.println(namesSort);

        if(namesSort.isEmpty()){
            throw new RuntimeException("文件列表为空");
        }

        File execFile = new File(dirPath, "merge.sh");

        StringBuilder cmd = new StringBuilder();
        cmd.append("cd ").append(dirPath).append("\n ");
        cmd.append("cat ");
        String fileStr = Joiner.on(" ").join(namesSort);
        cmd.append(fileStr);
        cmd.append(" > ").append(finalFileName);

        log.info("execute cmd: " + cmd);
        try {
            FileUtils.write(execFile, cmd.toString());
            Utils.executeCmd("sh " + execFile.getAbsolutePath(), dirPath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        log.info("merge " + dirPath + " success!");

        return Arrays.asList(new File(dir, finalFileName).getAbsolutePath());
    }


}
